package com.zhiche.lisa.core.utils.IOUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 网络读取文件工具
 *
 * @author qichao
 * @create 2018-06-29
 **/
public class UriIOUtil {
	private static final Logger logger = LoggerFactory.getLogger(UriIOUtil.class);
	/**
	 * 根据url拿取file
	 *
	 * @param url
	 * @param suffix
	 *            文件后缀名
	 * */
	public static File createFileByUrl(String url, String suffix) {
		byte[] byteFile = getFileByteFromUrl(url);
		if (byteFile != null) {
			File file = getFileFromBytes(byteFile, suffix);
			return file;
		} else {
			logger.info("生成文件失败！");
			return null;
		}
	}

	/**
	 * 根据地址获得数据的字节流
	 *
	 * @param strUrl
	 *            网络连接地址
	 * @return
	 */
	private static byte[] getFileByteFromUrl(String strUrl) {
		try {
			URL url = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
			byte[] btfile = readInputStream(inStream);// 得到图片的二进制数据
			return btfile;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 从输入流中获取数据
	 *
	 * @param inStream
	 *            输入流
	 * @return
	 * @throws Exception
	 */
	private static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}

	// 创建临时文件
	private static File getFileFromBytes(byte[] b, String suffix) {
		BufferedOutputStream stream = null;
		File file = null;
		try {
			file = File.createTempFile("pattern", "." + suffix);
			logger.info("临时文件位置："+file.getCanonicalPath());
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
			/**
			 * 程序运行结束后，删除文件
			 */
//			file.deleteOnExit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return file;
	}
}
